 // pkgPublish/pages/postPublish/index.js
 import QQMap from '../../../utils/qqMap'
 import {
   topicTypeList,
   addTopicType
 } from '../../../api/ChatTopicTypeController.js'
 const app = getApp()
 import {
   sendTopic
 } from '../../../api/ChatTopicController.js'
 import {
   delFile
 } from '../../../api/OssController.js'
 Page({
   /**
    * 页面的初始数据
    */
   data: {
     titleError: '',
     contentError: '',
     form: {
       city: '合肥市', //发帖位置
       file: wx.getStorageSync('file') || [], //发帖图片
       topicType: '', //话题ID
     },
     title: '', //发帖标题
     content: '', //发帖内容
     userLocation: '添加地点',
     tags: {
       name: '话题',
       type: ''
     },
     tagsList: [],
     value: '',
     show: false, //控制弹窗的显示隐藏,
     tagsShow: false //控制选择话题弹窗
   },
   //获取热门话题
   async getTopicTypeTopN() {
     const params = {
       pageNum: 1,
       pageSize: 10,
       userId: wx.getStorageSync('userId') || '1'
     }
     const res = await topicTypeList(params)
     this.setData({
       tagsList: res.list
     })
   },
   // 取消错误提示
   titleChange() {
     if (this.data.title) {
       this.setData({
         titleError: ''
       })
     }
   },
   contentChange() {
     if (this.data.content) {
       this.setData({
         contentError: ''
       })
     }
   },
   // 获取用户位置
   getLocation() {
     wx.chooseLocation({
       success: (res) => {
         QQMap.reverseGeocoder({
           location: {
             latitude: res.latitude,
             longitude: res.longitude
           },
           success: (res) => {
             console.log(res);
             const data = {
               provinceCode: res.result.ad_info.adcode,
               cityCode: res.result.ad_info.city_code,
               regionCode: '100',
               province: res.result.address_component.province,
               city: res.result.address_component.city
             }
             wx.setStorageSync('userLocation', data)
             app.userLocation = data
             this.setData({
               userLocation: app.userLocation.city + '·' + res.result.formatted_addresses.recommend
             })
           }
         })
       }
     })
     // wx.navigateTo({
     //   url: '/pkgUser/pages/location/index',
     // })
   },
   //上传图片
   afterRead(event) {
     const {
       file
     } = event.detail;
     // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
     file.forEach(ele => {
       const type = ele.type
       const uploadTask = wx.uploadFile({
         url: 'https://zhenpufangwu.cn:9000/utopia/admin/oss/uploadFile',
         filePath: ele.tempFilePath || ele.url,
         name: 'file',
         formData: {
           user: 'test',
           userId: app.userId
         },
         success: ({
           statusCode,
           data
         }) => {
           if (statusCode !== 200) return wx.utils.toast('上传失败！')
           // 上传完成需要更新 file
           const fList = [...this.data.form.file]
           fList.push({
             url: JSON.parse(data).data,
             type
           });
           this.setData({
             'form.file': fList,
           });
           wx.setStorageSync('file', fList)
         },
         fail() {
           wx.utils.toast('上传失败!')
         },
         complete: () => {
           wx.hideLoading()
         },
       });
       uploadTask.onProgressUpdate((res) => {
         wx.showLoading({
           title: '文件上传中...'
         })
       })
     })
   },
   //删除图片功能
   async delImage(ev) {
     const index = ev.detail.index
     const file = this.data.form.file
     await delFile(file[index].url)
     const newFile = file.filter(ele => ele.url !== file[index].url)
     this.setData({
       'form.file': newFile
     })
     wx.setStorageSync('file', newFile)
   },
   //关闭弹窗
   onClose() {
     this.setData({
       show: false
     })
   },
   //打开弹窗
   onOpen() {
     if (!this.data.title) return this.setData({
       titleError: '请输入标题'
     })
     if (!this.data.content) return this.setData({
       contentError: '请输入正文内容'
     })
     if (this.data.form.file.length < 1) return wx.utils.toast('最少选择一张图片')
     if (!this.data.tags.type) return wx.utils.toast('请选择话题')
     if (!this.data.form.city) return wx.utils.toast('请选择您的位置')
     this.setData({
       show: true
     })
   },
   //打开选择话题弹窗
   showTags() {
     this.setData({
       tagsShow: true
     })
   },
   //打开弹层前获取最新话题
   tagsOpen() {
     this.getTopicTypeTopN()
   },
   //关闭选择话题弹窗
   tagsOnClose() {
     this.setData({
       tagsShow: false
     })
   },
   //添加新话题
   async addTopictype() {
     if (!this.data.value) return
     const res = await addTopicType({
       name: this.data.value,
       userId: wx.getStorageSync('userId') || '1'
     })
     this.setData({
       'tags.name': res.name,
       'tags.type': res.typeId,
       tagsShow: false,
       value: ''
     })
   },
   //选中话题
   selectTag(ev) {
     this.setData({
       tags: {
         name: ev.mark.tags.name,
         type: ev.mark.tags.typeId
       },
       tagsShow: false
     })
   },
   //发布帖子
   async send() {
     this.setData({
       show: false
     })
     if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录')
     const file = this.data.form.file.map(ele => ele.url)
     const {
       provinceCode,
       cityCode,
       city,
       regionCode
     } = app.userLocation
     const user = {
       provinceCode,
       cityCode,
       regionCode,
       location: city,
       content: this.data.content,
       title: this.data.title,
       file,
       topicType: this.data.tags.type,
       userId: wx.getStorageSync('userId')
     }
     await sendTopic(user)
     wx.utils.toast('发布成功')
     wx.removeStorageSync('file')
     setTimeout(() => {
       wx.redirectTo({
         url: '/pkgUser/pages/myPost/index',
       })
     }, 500);
   },
   onChange() {},
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad({
     title
   }) {
     if (title) {
       wx.setNavigationBarTitle({
         title,
       })
     }
   },

   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady() {

   },

   /**
    * 生命周期函数--监听页面显示
    */
   onShow() {
     if (app.userLocation?.province) {
       this.setData({
         ['form.city']: app.userLocation.city,
         userLocation: app.userLocation.city
       })
     }
   },

   /**
    * 生命周期函数--监听页面隐藏
    */
   onHide() {

   },

   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload() {

   },

   /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh() {

   },

   /**
    * 页面上拉触底事件的处理函数
    */
   onReachBottom() {

   },

   /**
    * 用户点击右上角分享
    */
   onShareAppMessage() {

   }
 })